import { Message, ChatHistory, SSETextData, SSEAudioData } from '../pages/Chat/Components/types';
import { request } from '@/api/request';
import { getNodeApiUrlSync, getApiBaseUrlSync } from '../utils/apiConfig';
import { refreshTokenBalance } from '@/components/TokenBalance';
import { messageApi } from '@/hooks/messageApi';
import { message } from 'antd';

// Token预留结果接口
interface TokenReservationResult {
  success: boolean;
  reserve_id?: string;
  reserved?: number;
  expires_at?: string;
  balance_after?: number;
  message?: string;
  // 错误情况
  error?: string;
  current_balance?: number;
  required?: number;
}

/**
 * 聊天服务类
 * 处理消息发送、SSE连接、localStorage管理等
 */
export class ChatService {
  private chatId: string;
  private token: string | null = null;
  private eventSource: EventSource | null = null;
  private onMessageCallback?: (message: Message) => void;
  private onStreamUpdateCallback?: (messageId: string, content: string, done: boolean) => void;
  private uuid: string | null = null;
  private isCurrentPage: boolean = false; // 新增：标记是否是当前页面
  private translateFunction: ((key: string, params?: any) => string) | null = null; // 新增：翻译函数
  // 新增: 音频缓存相关
  private audioBufferCache = new Map<string, AudioBuffer>();
  private audioContext: AudioContext | null = null;

  constructor(chatId: string, token?: string) {
    this.chatId = chatId;
    this.token = token || null;
    // 获取localStorage中的visitor_uuid
    try {
      const userDataStr = localStorage.getItem('userData');
      if (userDataStr) {
        const userData = JSON.parse(userDataStr);
        this.uuid = userData.visitor_uuid || null;
      }
    } catch (e) {
      this.uuid = null;
    }

    // 检查是否是当前页面的聊天
    this.updateCurrentPageStatus();
  }

  // 设置翻译函数
  setTranslationFunction(translateFn: (key: string, params?: any) => string) {
    this.translateFunction = translateFn;
  }

  // 获取翻译文本的私有方法
  private getText(key: string, params?: any): string {
    if (this.translateFunction) {
      try {
        return this.translateFunction(key, params);
      } catch (error) {
        console.warn('Translation failed for key:', key, error);
      }
    }
    // 如果翻译失败，返回key作为默认值
    return key;
  }

  // 更新token
  setToken(token: string) {
    this.token = token;
  }

  // 检查并更新当前页面状态
  private updateCurrentPageStatus() {
    try {
      // 检查当前URL是否为聊天页面
      const currentUrl = window.location.pathname;
      const isConversationPage = currentUrl === '/conversation';

      // 如果是聊天页面，从sessionStorage获取当前聊天ID
      const currentChatId = isConversationPage ? sessionStorage.getItem('currentConversationId') : null
      this.isCurrentPage = isConversationPage && currentChatId === this.chatId;
    } catch (e) {
      console.error(this.getText('chatService.logs.pageStatusCheckFailed'), e);
      this.isCurrentPage = false;
    }
  }

  // 设置回调函数
  setCallbacks(callbacks: {
    onMessage?: (message: Message) => void;
    onStreamUpdate?: (messageId: string, content: string, done: boolean) => void;
  }) {
    this.onMessageCallback = callbacks.onMessage;
    this.onStreamUpdateCallback = callbacks.onStreamUpdate;
  }

  // 预留对话tokens
  private async reserveTokens(serviceType: 'text' | 'voice' | 'img', amount: number): Promise<string> {
    try {
      // 使用 request.post 发送请求
      const res = await request.post('/api/tokens/reserve', {
        user_uuid: this.uuid,
        service_type: serviceType,
        amount: amount
      });
      const result: TokenReservationResult = res.data;
      if (res.status !== 200) {
        console.error(`${this.getText('chatService.logs.tokenReservationFailed')} HTTP ${res.status}`, result);
      }
      if (!result.success || !result.reserve_id) {
        throw new Error(result.message || this.getText('chatService.errors.tokenReservationFailedNoReserveId'));
      }
      // 预留成功后，触发余额刷新
      setTimeout(() => {
        refreshTokenBalance();
      }, 500);
      return result.reserve_id;
    }
    catch (error: any) {
      // 判断错误类型 
      if (error.response?.data?.error === 'Insufficient tokens') {
        const insufficientError = new Error('Insufficient tokens') as any;
        insufficientError.isInsufficientTokens = true;
        insufficientError.currentBalance = error.response.data.current_balance;
        insufficientError.required = error.response.data.required;
        insufficientError.serviceType = serviceType;
        throw insufficientError;
        // throw new Error(result.error || this.getText('chatService.errors.tokenReservationFailedWithStatus', { status: res.status }));

      } else {
        message.error(this.getText('chatService.errors.networkError'));
      }
      throw error;
    }
  }

  // 缓存聊天历史，避免频繁读取localStorage
  private cachedHistory: ChatHistory | null = null;
  private cacheTimestamp: number = 0;
  private readonly CACHE_DURATION = 5000; // 5秒缓存

  // 从localStorage获取聊天历史 - 添加缓存优化
  getChatHistory(): ChatHistory {
    const now = Date.now();

    // 如果有有效缓存，直接返回
    if (this.cachedHistory && (now - this.cacheTimestamp) < this.CACHE_DURATION) {
      return { ...this.cachedHistory };
    }

    try {
      const stored = localStorage.getItem(`chat_history_${this.chatId}`);
      if (stored) {
        this.cachedHistory = JSON.parse(stored);
        this.cacheTimestamp = now;
        return this.cachedHistory!;
      }
    } catch (error) {
      console.error('Error loading chat history:', error);
    }

    const defaultHistory = { messages: [] };
    this.cachedHistory = defaultHistory;
    this.cacheTimestamp = now;
    return defaultHistory;
  }

  // 保存聊天历史到localStorage - 添加防抖优化
  private saveTimeout: NodeJS.Timeout | null = null;

  saveChatHistory(history: ChatHistory) {
    // 更新缓存
    this.cachedHistory = history;
    this.cacheTimestamp = Date.now();

    // 防抖保存到localStorage，避免频繁写入
    if (this.saveTimeout) {
      clearTimeout(this.saveTimeout);
    }

    this.saveTimeout = setTimeout(() => {
      try {
        localStorage.setItem(`chat_history_${this.chatId}`, JSON.stringify(history));
      } catch (error) {
        console.error('Error saving chat history:', error);
      }
    }, 200); // 200ms防抖
  }

  // 添加消息到历史记录
  addMessage(message: Message): ChatHistory {
    const history = this.getChatHistory();
    history.messages.push(message);
    this.saveChatHistory(history);
    return history;
  }

  // 更新消息状态
  updateMessage(messageId: string, updates: Partial<Message>): ChatHistory {
    const history = this.getChatHistory();
    const messageIndex = history.messages.findIndex(m => m.id === messageId);
    if (messageIndex !== -1) {
      history.messages[messageIndex] = { ...history.messages[messageIndex], ...updates };
      this.saveChatHistory(history);
    }
    return history;
  }

  // 更新session_id
  updateSessionId(sessionId: string) {
    const history = this.getChatHistory();
    history.sessionId = sessionId;
    this.saveChatHistory(history);
  }

  // 删除completeAudioMessage中关于OSS上传的调用和逻辑，保留本地base64处理
  async completeAudioMessage(messageId: string, duration: number, audioData: string) {
    // 只做本地状态更新，不再上传到OSS
    const updatedHistory = this.updateMessage(messageId, {
      status: 'completed',
      isStreaming: false,
      isPlaying: false,
      duration,
      audioData: audioData || '' // 仍然存储base64或URL
    });

    // 通知UI更新
    const updatedMessage = updatedHistory.messages.find(m => m.id === messageId);
    if (updatedMessage) {
      this.onMessageCallback?.(updatedMessage);
    } else {
      console.warn('🎵 ChatService: Audio message not found for update', messageId);
    }
  }

  // 发送文本消息
  async sendTextMessage(content: string, language: string): Promise<string> {
    // 检测是否有特殊的图片URL标记
    const isImageResult = content.includes('[画像が生成されました]');

    const history = this.getChatHistory();
    const messageId = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // 提取图片URL并创建正确类型的消息
    if (isImageResult) {
      // 从消息中提取图片URL
      const imageUrlMatch = content.match(/\[画像が生成されました\]\s*(https?:\/\/\S+)/i);
      const imageUrl = imageUrlMatch ? imageUrlMatch[1] : '';

      if (imageUrl) {
        // 添加AI图片消息
        const imageMessage: Message = {
          id: messageId,
          type: 'image',
          content: this.getText('imageService.generatedImage'),
          sender: 'ai',
          timestamp: Date.now(),
          status: 'completed',
          imageUrl,
          receivedAt: Date.now()
        };

        this.addMessage(imageMessage);
        this.onMessageCallback?.(imageMessage);
        return messageId;
      }
    }

    // 正常的文本消息处理
    const userMessage: Message = {
      id: messageId,
      type: 'text',
      content,
      sender: 'user',
      timestamp: Date.now(),
      status: 'sending'
    };

    // 立即显示用户消息，提升用户体验
    this.addMessage(userMessage);
    this.onMessageCallback?.(userMessage);

    // 🪙 然后预留tokens
    let reserveId: string;
    try {
      reserveId = await this.reserveTokens('text', 1);
    } catch (error) {
      console.error(this.getText('chatService.logs.textMessageTokenReservationFailed'), error);
      throw error; // 直接抛出原始错误，让上层处理
    }

    try {
      // 准备请求数据
      const requestData = {
        messages: [{ role: 'user', content }],
        session_id: history.sessionId,
        stream: true,
        generate_voice: false,
        chat_id: this.chatId,
        language,
        reserve_id: reserveId, // 🪙 添加预留ID
        uuid: this.uuid // 添加uuid参数
      };

      // 更新用户消息状态为已发送
      this.updateMessage(messageId, { status: 'completed' });

      // 创建AI消息 - 初始状态为sending（等待中），用于显示loading动画
      const aiMessageId = `ai_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const aiMessage: Message = {
        id: aiMessageId,
        type: 'text',
        content: '',
        sender: 'ai',
        timestamp: Date.now(),
        status: 'sending', // 初始状态为sending，MessageBubble会显示loading动画
        isStreaming: false
      };

      this.addMessage(aiMessage);
      this.onMessageCallback?.(aiMessage);

      // 发起SSE连接
      await this.startSSEConnection(requestData, aiMessageId);

      return messageId;
    } catch (error) {
      console.error('Error sending text message:', error);
      this.updateMessage(messageId, { status: 'failed' });
      throw error;
    }
  }

  // 发送语音消息
  async sendVoiceMessage(content: string, language: string, isMobile: boolean = false): Promise<string> {
    const history = this.getChatHistory();
    const messageId = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // 1. 先展示用户发送的文本消息
    const userMessage: Message = {
      id: messageId,
      type: 'text', // 用户输入的是文本，但会生成语音回复
      content,
      sender: 'user',
      timestamp: Date.now(),
      status: 'sending'
    };
    this.addMessage(userMessage);
    this.onMessageCallback?.(userMessage);

    // 3. 预留tokens
    let reserveId: string;
    try {
      reserveId = await this.reserveTokens('voice', 2);
    } catch (error) {
      console.error(this.getText('chatService.logs.voiceMessageTokenReservationFailed'), error);
      throw error; // 直接抛出原始错误，让上层处理
    }

    try {
      // 准备请求数据 - PC端和移动端都使用非流式响应
      const requestData = {
        messages: [{ role: 'user', content }],
        session_id: history.sessionId,
        stream: false, // PC端和移动端都设置为false，使用非流式请求
        generate_voice: true,
        chat_id: this.chatId,
        language,
        reserve_id: reserveId, // 🪙 添加预留ID
        uuid: this.uuid // 添加uuid参数
      };

      // 更新用户消息状态为已发送
      this.updateMessage(messageId, { status: 'completed' });

      // 创建AI语音消息 - 初始状态为sending（等待中），用于显示loading动画
      const aiMessageId = `ai_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const aiMessage: Message = {
        id: aiMessageId,
        type: 'audio',
        content: '',
        sender: 'ai',
        timestamp: Date.now(),
        status: 'sending', // 初始状态为sending，MessageBubble会显示loading动画
        isStreaming: false
      };

      this.addMessage(aiMessage);
      this.onMessageCallback?.(aiMessage);

      // PC端和移动端都使用非流式请求
      await this.sendNonStreamVoiceRequest(requestData, aiMessageId);

      return messageId;
    } catch (error) {
      console.error('Error sending voice message:', error);
      this.updateMessage(messageId, { status: 'failed' });
      throw error;
    }
  }

  // 发送非流式语音请求
  private async sendNonStreamVoiceRequest(requestData: any, messageId: string): Promise<void> {
    const apiBaseUrl = getApiBaseUrlSync();

    // 准备请求头
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'application/json', // 非流式响应
    };

    // 添加token到请求头
    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`;
    }

    try {
      const response = await fetch(`${apiBaseUrl}/chat/`, {
        method: 'POST',
        headers,
        body: JSON.stringify(requestData)
      });

      if (response.status === 500) {
        console.error('Language generation failed');
      }
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      // console.log('🎵 Received non-streaming response:', {
      //   messageId,
      //   hasText: !!data.text,
      //   hasAudio: !!data.audio,
      //   hasHistory: !!data.history
      // });

      // 处理非流式响应
      await this.handleNonStreamResponse(data, messageId);

    } catch (error) {
      console.error('🎵 Non-streaming request failed:', error);

      // 更新消息状态为失败
      this.updateMessage(messageId, { status: 'failed' });

      // 获取更新后的消息并触发回调，确保UI立即更新
      const failedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
      if (failedMessage && this.onMessageCallback) {
        // console.log('🎵 Notifying UI to update failed status:', failedMessage.id);
        this.onMessageCallback(failedMessage);
      }

      // 不再抛出错误，避免中断处理流程
      // throw error;
    }
  }

  // 处理非流式响应数据
  private async handleNonStreamResponse(data: any, messageId: string) {
    try {
      // 更新session_id
      if (data.session_id) {
        this.updateSessionId(data.session_id);
      }

      // 更新消息内容
      const content = data.text || 'Voice message';
      this.updateMessage(messageId, {
        content,
        status: 'completed',
        isStreaming: false,
        receivedAt: Date.now()
      });

      // 只处理OSS URL音频
      if (data.audio && data.audio.oss_url) {
        const audioDuration = data.audio.duration || 1;
        this.updateMessage(messageId, {
          audioData: data.audio.oss_url, // 只存储URL
          duration: audioDuration,
          status: 'sending',
          isStreaming: false,
          isAudioPreloaded: false
        });
        // 通知组件立即更新UI
        const updatedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
        if (updatedMessage) {
          this.onMessageCallback?.(updatedMessage);
        }
        // 立即开始预加载音频
        this.preloadOssAudio(messageId, data.audio.oss_url);
      }

      // 更新历史记录的最后一条消息
      if (content && this.onStreamUpdateCallback) {
        this.onStreamUpdateCallback(messageId, content, true);
      }
    } catch (error) {
      console.error('🎵 Failed to process non-streaming response:', error);
      this.updateMessage(messageId, { status: 'failed' });
      // 通知UI更新失败状态
      const failedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
      if (failedMessage && this.onMessageCallback) {
        this.onMessageCallback(failedMessage);
      }
    }
  }

  // 启动SSE连接
  private async startSSEConnection(requestData: any, messageId: string): Promise<void> {
    return new Promise((resolve, reject) => {
      // 关闭现有连接
      this.closeSSEConnection();

      // 获取API基础URL
      const apiBaseUrl = getApiBaseUrlSync();
      // 记录请求开始时间
      const requestStartTime = Date.now();
      // 准备请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
      };

      // 添加token到请求头
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      // 发起POST请求建立SSE连接
      fetch(`${apiBaseUrl}/chat/`, {
        method: 'POST',
        headers,
        body: JSON.stringify(requestData)
      })
        .then(response => {
          if (response.status === 500) {
            console.error('Language generation failed');
          }
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          // 创建EventSource来处理SSE流
          const reader = response.body?.getReader();
          if (!reader) {
            throw new Error('No response body reader available');
          }

          this.processSSEStream(reader, messageId, resolve, reject);
        })
        .catch(error => {
          console.error('SSE connection error:', error);
          // console.log('Request timeout')
          this.updateMessage(messageId, { status: 'failed' });

          // 通知UI更新，确保loading状态被清除
          const failedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
          if (failedMessage) {
            this.onMessageCallback?.(failedMessage);
          }

          reject(error);
        });
    });
  }

  // 处理SSE流 - 立即处理每一行以实现真正的流式效果
  private async processSSEStream(
    reader: ReadableStreamDefaultReader<Uint8Array>,
    messageId: string,
    resolve: () => void,
    reject: (error: any) => void
  ) {
    const decoder = new TextDecoder();
    let buffer = '';
    let firstDataReceived = false;
    const streamStartTime = Date.now();

    try {
      while (true) {
        const { done, value } = await reader.read();

        if (done) {
          // 流结束，完成消息
          console.error('SSE connection disconnected');
          this.updateMessage(messageId, { status: 'completed', isStreaming: false });
          resolve();
          break;
        }

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || ''; // 保留最后一个不完整的行

        for (const line of lines) {
          if (line.trim()) {
            // 记录第一个数据块的接收时间，并更新消息状态为streaming
            if (!firstDataReceived && (line.startsWith('data:') || line.startsWith('event:'))) {
              const firstDataTime = Date.now() - streamStartTime;
              firstDataReceived = true;
              // 将AI消息状态从'sending'更新为'streaming'
              this.updateMessage(messageId, { status: 'streaming', isStreaming: true });
            }

            // 立即处理每一行，实现真正的流式效果
            this.processSSELine(line, messageId);
          }
        }
      }
    } catch (error) {
      console.error('SSE connection disconnected');
      console.error('Error processing SSE stream:', error);
      this.updateMessage(messageId, { status: 'failed', isStreaming: false });

      // 通知UI更新，确保loading状态被清除
      const failedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
      if (failedMessage) {
        this.onMessageCallback?.(failedMessage);
      }

      reject(error);
    }
  }

  // 处理单行SSE数据
  private processSSELine(line: string, messageId: string) {
    if (line.startsWith('event: ')) {
      const eventType = line.substring(7).trim();
      if (eventType === 'done') {
        // 处理流式结束事件，只对文本消息生效
        const currentMessage = this.getChatHistory().messages.find(m => m.id === messageId);
        if (currentMessage && currentMessage.type === 'text' && currentMessage.status === 'streaming') {
          this.updateMessage(messageId, { status: 'completed', isStreaming: false });
            // 通知流更新回调，标记为完成
          this.onStreamUpdateCallback?.(messageId, currentMessage.content || '', true);

          // 流式文本响应完成后立即调用 Edit-ChatStatus
          this.callEditChatStatusAfterStream(messageId);
        }
      }
      return;
    }

    if (line.startsWith('data: ')) {
      try {
        const data = JSON.parse(line.substring(6));
        if (data.session_id) {
          // 更新session_id
          this.updateSessionId(data.session_id);
        }

        // 新增：如果有accumulated字段，直接更新消息内容
        if (typeof data.accumulated === 'string') {
          this.updateMessage(messageId, { content: data.accumulated, status: 'streaming', isStreaming: true });
          this.onStreamUpdateCallback?.(messageId, data.accumulated, !!data.done);
          // 如果有done字段，流式结束
          if (data.done) {
            this.updateMessage(messageId, { status: 'completed', isStreaming: false });
            // 流式文本响应完成后立即调用 Edit-ChatStatus
            this.callEditChatStatusAfterStream(messageId);
          }
          return; // 不再走handleTextData
        }
        if (data.text !== undefined) {
          // 文本消息
          this.handleTextData(data as SSETextData, messageId);
        }
      } catch (error) {
        console.error('Error parsing SSE data:', error);
      }
    }
  }

  // 处理文本数据
  private handleTextData(data: SSETextData, messageId: string) {
    const currentMessage = this.getChatHistory().messages.find(m => m.id === messageId);
    if (currentMessage) {
      // 计算本次新增的文本块
      const prevContent = currentMessage.content || '';
      const newContent = data.text || '';
      let delta = newContent;
      if (prevContent && newContent.startsWith(prevContent)) {
        delta = newContent.slice(prevContent.length);
      }
      const updatedContent = prevContent + delta;
      this.updateMessage(messageId, { content: updatedContent });
      this.onStreamUpdateCallback?.(messageId, updatedContent, data.done);

      if (data.done) {
        this.updateMessage(messageId, { status: 'completed', isStreaming: false });

        // 流式文本响应完成后立即调用 Edit-ChatStatus
        this.callEditChatStatusAfterStream(messageId);
      }
    }
  }

  // 流式文本响应完成后调用 Edit-ChatStatus
  private async callEditChatStatusAfterStream(messageId: string): Promise<void> {
    try {
      // 重新检查当前页面状态，因为可能有页面切换
      this.updateCurrentPageStatus();
      // 只有当前页面的聊天才发起请求
      if (!this.isCurrentPage) {
        return;
      }
      const response = await request.post('/api/chat/Edit-ChatStatus', {
        id: Number(this.chatId),      // 当前AI的id
        chatId: messageId,            // 消息id
        ai_person_id: this.chatId     // 添加ai_person_id参数，值为当前对话的机器人id
      });
      // 更新本地消息状态为已读
      this.updateMessage(messageId, { status: 'Read' });
    } catch (error) {
      console.error(this.getText('chatService.logs.editChatStatusFailed'), error);
    }
  }
  // 处理音频数据 - 已移除，改为在handleNonStreamResponse中直接处理非流式音频响应
  // 关闭SSE连接
  closeSSEConnection() {
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
      console.error('SSE connection disconnected');
    }
  }

  // 新增: 初始化音频上下文
  private initAudioContext() {
    if (!this.audioContext) {
      try {
        const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext;
        if (AudioContextClass) {
          this.audioContext = new AudioContextClass();
        }
      } catch (error) {
        // console.error('🎵 初始化AudioContext失败:', error);
        console.error('initAudioContext failed');
      }
    }
    return this.audioContext;
  }

  // 新增: 预加载和解码OSS音频
  async preloadOssAudio(messageId: string, audioUrl: string) {
    try {
      // 初始化AudioContext
      const audioContext = this.initAudioContext();
      if (!audioContext) {
        // console.warn('🎵 AudioContext不可用，无法预加载音频');
        console.warn('AudioContext is not available, cannot preload audio');
        // AudioContext不可用时也要将消息状态设为可播放
        this.updateMessage(messageId, {
          canPlay: true,
          status: 'completed',
          isAudioPreloaded: false
        });

        // 通知UI更新
        const updatedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
        if (updatedMessage) {
          this.onMessageCallback?.(updatedMessage);
        }
        return;
      }

      // 如果已经缓存，则跳过
      if (this.audioBufferCache.has(messageId)) {
        // console.log('🎵 音频已缓存，直接更新状态:', messageId);
        // 已缓存，直接更新状态
        this.updateMessage(messageId, {
          canPlay: true,
          status: 'completed',
          isAudioPreloaded: true
        });

        // 通知UI更新
        const updatedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
        if (updatedMessage) {
          this.onMessageCallback?.(updatedMessage);
        }
        return;
      }

      // 获取音频数据
      const response = await fetch(audioUrl);
      if (!response.ok) throw new Error('Failed to fetch audio');

      const arrayBuffer = await response.arrayBuffer();

      // 解码音频数据
      const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

      // 缓存解码后的数据
      this.audioBufferCache.set(messageId, audioBuffer);

      // 预加载完成，更新消息状态为已预加载、可播放状态
      this.updateMessage(messageId, {
        canPlay: true,
        status: 'completed',
        isAudioPreloaded: true
      });
      // console.log('🎵 音频预加载完成，已更新消息状态:', messageId);

      // 通知UI更新
      const updatedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
      if (updatedMessage) {
        this.onMessageCallback?.(updatedMessage);
      }
    } catch (error) {
      // console.error('🎵 音频预加载失败:', error);
      console.error('preloadOssAudio failed');
      // 预加载失败，也要将消息状态更新为可播放
      this.updateMessage(messageId, {
        canPlay: true,
        status: 'completed',
        isAudioPreloaded: false
      });

      // 通知UI更新
      const updatedMessage = this.getChatHistory().messages.find(m => m.id === messageId);
      if (updatedMessage) {
        this.onMessageCallback?.(updatedMessage);
      }
    }
  }

  // 新增: 从缓存播放音频的方法
  playAudioFromCache(messageId: string): { success: boolean; source?: AudioBufferSourceNode; context?: AudioContext } {
    try {
      const audioBuffer = this.audioBufferCache.get(messageId);
      if (!audioBuffer) return { success: false };

      const audioContext = this.initAudioContext();
      if (!audioContext) return { success: false };

      const source = audioContext.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(audioContext.destination);

      return { success: true, source, context: audioContext };
    } catch (error) {
      // console.error('🎵 从缓存播放音频失败:', error);
      console.error('playAudioFromCache failed');
      return { success: false };
    }
  }

  // 清理资源 - 优化版本
  destroy() {
    this.closeSSEConnection();

    // 清理防抖定时器
    if (this.saveTimeout) {
      clearTimeout(this.saveTimeout);
      this.saveTimeout = null;
    }

    // 清理缓存
    this.cachedHistory = null;
    this.cacheTimestamp = 0;

    // 清理音频缓存
    this.audioBufferCache.clear();
    if (this.audioContext) {
      try {
        if (this.audioContext.state !== 'closed') {
          this.audioContext.close();
        }
      } catch (e) {
        // console.error('关闭AudioContext失败:', e);
        console.error('closeAudioContext failed');
      }
      this.audioContext = null;
    }

    // 重置回调函数
    this.onMessageCallback = undefined;
    this.onStreamUpdateCallback = undefined;
  }

  // 获取初始问候语
  async getInitialGreeting(userData: any, aiPersonId: string, language: string): Promise<{ image: string, text: string } | null> {
    try {
      if (!userData || !userData.visitor_uuid) {
        console.error('❌ Failed to get initial greeting: User data or UUID does not exist');
        return null;
      }

      const apiBaseUrl = getNodeApiUrlSync();
      const url = `${apiBaseUrl}/api/ai-chat/initial-greeting`;

      // console.log(`🚀 Initiating initial greeting request: ${url}`);

      // 准备请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      // 添加token到请求头
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
        // console.log('✅ Authentication token added to request headers');
      } else {
        console.warn('⚠️ No token for initial greeting request');
      }

      // 准备请求体
      const requestBody = {
        uuid: userData.visitor_uuid,
        aiPersonId,
        language
      };

      // console.log('📦 Initial greeting request parameters:', JSON.stringify(requestBody));

      // 发送请求
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        const errorText = await response.text().catch(() => 'Unable to get error details');
        console.error(`❌ Initial greeting API request failed: HTTP ${response.status}`, errorText);
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 解析响应
      let data;
      try {
        data = await response.json();
        // console.log('📩 Received initial greeting API response:', data);
      } catch (parseError) {
        console.error('❌ Failed to parse initial greeting response:', parseError);
        throw new Error('Unable to parse API response');
      }

      if (data.success && data.data) {
        return {
          image: data.data.image,
          text: data.data.text
        };
      } else {
        console.error('❌ Invalid initial greeting data format:', data);
        return null;
      }
    } catch (error) {
      console.error('❌ Error getting initial greeting:', error);
      return null;
    }
  }

  // 添加初始问候图片消息和文本消息（拆分为两条消息）
  addInitialGreetingMessages(imageUrl: string, textContent: string): { imageMessageId: string, textMessageId: string } {
    // console.log('🎬 Adding initial greeting, split into image and text messages');
    // 1. 创建图片消息ID
    const imageMessageId = `ai_img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    // 2. 预生成文本消息ID
    const textMessageId = `ai_text_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    // 检查图片URL是否为空，如果为空则跳过添加图片消息
    if (!imageUrl || imageUrl === '') {
      // console.log('初始问候图片URL为空，跳过图片消息创建和同步');

      // 检查文本内容是否为空，不为空才创建文本消息
      if (textContent && textContent.trim() !== '') {
        this.simulateStreamInitialGreeting(textContent, textMessageId);
      } else {
        // console.log('初始问候文本内容为空，跳过文本消息创建');
      }

      return {
        imageMessageId,
        textMessageId
      };
    }

    // 图片URL不为空，创建图片消息对象
    const imageMessage: Message = {
      id: imageMessageId,
      type: 'image',
      content: '',
      sender: 'ai',
      timestamp: Date.now(),
      receivedAt: Date.now(),
      status: 'completed',
      imageUrl: imageUrl
    };

    // console.log('Getting initial greeting image message:', imageMessage);

    // 将初始问候图片消息数据同步到数据库 
    request.post('/api/chat/UpData-ChatHistoryMessage', {
      uuid: this.uuid,
      id: this.chatId,
      messages: [imageMessage],
      sessionId: this.getChatHistory().sessionId,
    }).then(res => {
      if (res.data.success === true) {
        // 添加图片消息到历史记录
        this.addMessage(imageMessage);

        // 触发消息回调
        if (this.onMessageCallback) {
          this.onMessageCallback(imageMessage);
          // console.log('📢 Image message added, ID:', imageMessageId);
        }

        // 图片消息同步成功后，检查文本内容是否为空，不为空才创建文本消息
        if (textContent && textContent.trim() !== '') {
          setTimeout(() => {
            this.simulateStreamInitialGreeting(textContent, textMessageId);
          }, 500);
        } else {
          // console.log('初始问候文本内容为空，跳过文本消息创建');
        }
      }
    }).catch(err => {
      console.error('Failed to sync initial greeting image message to database:', err);
    })

    return {
      imageMessageId,
      textMessageId
    };
  }

  // 模拟流式传输初始问候文本
  simulateStreamInitialGreeting(textContent: string, messageId?: string): string {
    // 如果文本内容为空，直接返回messageId，不执行任何操作
    if (!textContent || textContent.trim() === '') {
      return messageId || `ai_text_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
    // 使用传入的messageId或生成新的
    const finalMessageId = messageId || `ai_text_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // 创建初始消息对象 - 纯文本，无图片
    const message: Message = {
      id: finalMessageId,
      type: 'text',
      content: '',
      sender: 'ai',
      timestamp: Date.now(),
      status: 'streaming',
      isStreaming: true
    };

    // console.log('Getting initial greeting text message:', textContent);

    // 将初始问候文本消息数据同步到数据库 
    request.post('/api/chat/UpData-ChatHistoryMessage', {
      uuid: this.uuid,
      id: this.chatId,
      messages: [{
        id: finalMessageId,
        type: 'text',
        content: textContent,
        sender: 'ai',
        timestamp: Date.now(),
        status: 'streaming',
        isStreaming: true
      }],
      sessionId: this.getChatHistory().sessionId,
    })

    // 添加到历史记录
    this.addMessage(message);

    // 打印当前ai的基础信息
    // console.log('Current AI basic information:', this.getChatHistory());

    // 触发消息回调
    if (this.onMessageCallback) {
      this.onMessageCallback(message);
      // console.log('📢 Initial greeting message callback triggered, message ID:', finalMessageId);
    } else {
      console.warn('⚠️ Initial greeting message callback not set');
    }

    // 模拟流式输入
    let currentPos = 0;
    const streamInterval = setInterval(() => {
      // 每次增加1-3个字符，随机变化速度
      const charsToAdd = Math.floor(Math.random() * 3) + 1;
      currentPos = Math.min(currentPos + charsToAdd, textContent.length);
      const currentContent = textContent.substring(0, currentPos);

      // 更新消息内容
      this.updateMessage(finalMessageId, { content: currentContent });

      // 调用流更新回调
      if (this.onStreamUpdateCallback) {
        this.onStreamUpdateCallback(finalMessageId, currentContent, currentPos >= textContent.length);
      }

      // 如果已到文本末尾，清除计时器并完成消息
      if (currentPos >= textContent.length) {
        clearInterval(streamInterval);
        this.updateMessage(finalMessageId, {
          status: 'completed',
          isStreaming: false,
          receivedAt: Date.now()
        });

        // console.log('✅ Initial greeting streaming completed, message ID:', finalMessageId);
      }
    }, 50); // 每50ms更新一次

    // 防止内存泄漏 - 在10秒后如果还没完成，强制清除计时器
    setTimeout(() => {
      clearInterval(streamInterval);

      // 检查消息状态，如果还是streaming则更新为completed
      const history = this.getChatHistory();
      const messageState = history.messages.find(m => m.id === finalMessageId);
      if (messageState && messageState.status === 'streaming') {
        // console.log('⚠️ Initial greeting streaming timeout, forcing completion');
        this.updateMessage(finalMessageId, {
          content: textContent, // 确保显示完整内容
          status: 'completed',
          isStreaming: false,
          receivedAt: Date.now()
        });

        // 通知UI更新
        if (this.onStreamUpdateCallback) {
          this.onStreamUpdateCallback(finalMessageId, textContent, true);
        }
      }
    }, 10000); // 10秒超时保护

    return finalMessageId;
  }

  clearChatHistory(): ChatHistory {
    this.cachedHistory = null;
    localStorage.removeItem(`chat_history_${this.chatId}`);
    return { messages: [] };
  }
}

/**
 * 删除聊天历史
 * @param chatId 聊天ID
 * @param uuid 用户UUID
 * @returns Promise 删除结果
 */
export const deleteChatHistory = async (chatId: string, uuid: string): Promise<{ success: boolean; message: string; deleted_records?: number }> => {
  try {

    const response = await request.post('/api/chat/Delete-ChatHistory', {
      id: chatId,
      uuid: uuid
    });

    if (response.data.success) {
      // console.log('✅ Chat history deleted successfully:', response.data);
      return response.data;
    } else {
      console.error('❌ Failed to delete chat history:', response.data);
      throw new Error(response.data.message || 'Delete failed');
    }
  } catch (error) {
    console.error('❌ Error deleting chat history:', error);
    throw error;
  }
};

/**
 * 重置聊天历史
 * @param chatId 聊天ID (机器人ID)
 * @param uuid 用户UUID
 * @returns Promise 重置结果
 */
export const refreshChatHistory = async (chatId: string, uuid: string): Promise<{ success: boolean; message: string; data?: any }> => {
  try {
    // console.log('🔄 Starting to reset chat history:', { chatId, uuid });

    const response = await request.post('/api/chat/Refresh-ChatHistory', {
      id: chatId,
      uuid: uuid
    });

    if (response.data.success) {
      // console.log('✅ Chat history reset successfully:', response.data);
      return response.data;
    } else {
      console.error('❌ Failed to reset chat history:', response.data);
      throw new Error(response.data.message || 'Reset failed');
    }
  } catch (error) {
    console.error('❌ Error resetting chat history:', error);
    throw error;
  }
}; 